package com.tct.smartRE.fwk.impl.service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.tct.smartRE.fwk.api.IBusinessObject;
import com.tct.smartRE.fwk.api.IQueryCondition;
import com.tct.smartRE.fwk.api.ParamType;
import com.tct.smartRE.fwk.api.dao.ICommonDAO;
import com.tct.smartRE.fwk.api.service.IDBService;
import com.tct.smartRE.fwk.domain.Property;
import com.tct.smartRE.fwk.impl.dao.QueryConditionTemplate;

public class PropertiesDBService extends CommonDBService implements IDBService {

	public PropertiesDBService(ICommonDAO dao) {
		super(dao);
	}

	@SuppressWarnings("unchecked")
	public Integer countByParam(Map<ParamType, Serializable> param) {
		Object[] queryParam = createQueryAndParam(param);
		
		final String sqlQuery = (String) queryParam[0];
		final List<Object> sqlParam = (List<Object>) queryParam[1];
		
		IQueryCondition query = QueryConditionTemplate.createQuery(sqlQuery, sqlParam);
		return countByCondition(query);
	}

	Object[] createQueryAndParam(Map<ParamType, Serializable> param) {
		Object[] result = new Object[2];
		List<Object> sqlParam = new ArrayList<Object>();
		String sqlString = "from " + Property.class.getSimpleName() + " as i ";
		
		//create sqlQuery and add parameter to sqlParam
		String joinWord = "where ";
		String address = (String) param.get(ParamType.Address); 
		if( address != null && address.trim().length() != 0) {
			sqlString += joinWord + "(lower(i.address) like ?) ";
			joinWord = "and ";
			sqlParam.add("%" + address.trim().toLowerCase() + "%");
		}
		
		//sort item list
		String sortColumn = (String) param.get(ParamType.SortColumn);
		String sortType = (String) param.get(ParamType.SortType);
		if (sortColumn != null && sortColumn.trim().length() > 0
				&& sortType != null && sortType.trim().length() > 0) {
			sqlString += "order by i.createdDate " + sortType + " ";
		}
		
		result[0] = sqlString;
		result[1] = sqlParam;
		return result;
	}

	@SuppressWarnings("unchecked")
	public List<IBusinessObject> findByParam(Map<ParamType, Serializable> param) {
		Object[] queryParam = createQueryAndParam(param);
		
		Integer firstResult = (Integer) param.get(ParamType.FirstResult);
		Integer maxResult = (Integer) param.get(ParamType.MaxResult);
		final String sqlQuery = (String) queryParam[0];
		final List<Object> sqlParam = (List<Object>) queryParam[1];
		
		IQueryCondition query = QueryConditionTemplate.createQuery(sqlQuery, sqlParam, firstResult, maxResult);
		return findByCondition(query);
	}

}
